using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.ServiceProcess;
using System.Windows.Forms;
using log4net;
using log4net.Config;
using Sedna.API.Remoting;
using Sedna.Core;
using Sedna.Core.Controller;
using Sedna.Core.Scheduler;

namespace Sedna.Template.Scheduler
{
    public class SchedulerProcess
    {
        private const string SCHEDULER_CONFIGURATION = "runtime.Scheduler";
        private ILog log = LogManager.GetLogger(typeof(SchedulerProcess));

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            new SchedulerProcess();
        }

        private SchedulerProcess()
        {
            XmlConfigurator.Configure();
            try
            {
                if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["trustAnyCertificate"]))
                    System.Net.ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(IsCertificateValid);

                RemotingConfigurator.Configure(Assembly.GetExecutingAssembly());

                log.Debug("Configuring services");

                ServiceBase[] ServicesToRun;

                ISchedulerConfiguration configuration =
                    (ISchedulerConfiguration)SpringContextFactory.GetContext().GetObject(SCHEDULER_CONFIGURATION);

                ServicesToRun = new ServiceBase[] { new Core.Scheduler.Scheduler(configuration) };

                ServiceBase.Run(ServicesToRun);

                log.Debug("Services configured");
            }
            catch (Exception e)
            {
                log.Error(e);
                throw new SednaException("Sedna.Template Scheduler service has returned with error", e);
            }
        }

        private bool IsCertificateValid(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
    }
}